package com.CommunityHub.kiana.controller;


import com.CommunityHub.kiana.po.User;
import com.CommunityHub.kiana.service.MemberService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/PurchaseHouseServlet")
public class PurchaseHouseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        User user = (User) session.getAttribute("user");
        int memberId = user.getId();
        int houseId = Integer.parseInt(request.getParameter("houseId"));

        MemberService memberService = new MemberService();
        try {
            if (memberService.purchaseHouse(memberId, houseId)) {
                // 重新加载完整会员信息
                MemberService.CompleteMemberInfo info =
                        memberService.getCompleteMemberInfo(memberId);
                session.setAttribute("memberInfo", info);

                response.sendRedirect("ViewPurchasedHousesServlet");
            } else {
                if (memberService.hasPurchasedHouse(memberId)) {
                    request.setAttribute("error", "您已购买了房产，无法再次购买");
                } else {
                    request.setAttribute("error", "购买失败，房源可能已被售出");
                }
                response.sendRedirect("HouseListServlet");
            }
        } catch (SQLException e) {
            request.setAttribute("error", "购买失败: " + e.getMessage());
            request.getRequestDispatcher("houseList.jsp").forward(request, response);
        }
    }
}